package images;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class APImage implements ImageObserver /* TODO: implements Iterable<APImagePixel> */ {

	/**
	 */
	private BufferedImage image;

	public APImage(BufferedImage image) {
		this.image = image;
	}

	/**
	 * This method gets a BufferedImage from a file.
	 * 
	 * @param file The file to get the image from
	 * @return Returns the image
	 * @throws IOException Throws an IOException if the file isn't found or if there is some kind of IO error.
	 */
	public static BufferedImage getImageFromFile(File file) throws IOException {
		BufferedImage image = ImageIO.read(file);
		while (image.getWidth() < 0)  // Wait for size to be known
			;
		return image;
	}
	
	public int getWidth() {
		return image.getWidth();
	}
	
	public int getHeight() {
		return image.getHeight();
	}

	public void createGrayImage() {
		int width = image.getWidth(this);
		int height = image.getHeight(this);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				APImagePixel pixel = new APImagePixel(image.getRGB(x, y));
				int red = pixel.getRed();
				int green = pixel.getGreen();
				int blue = pixel.getBlue();
				int average = (red + green + blue) / 3;
				pixel.setRed(average);
				pixel.setGreen(average);
				pixel.setBlue(average);
				image.setRGB(x, y, pixel.getValue());
			}
		}
	}

	@Override
	public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
		// TODO Auto-generated method stub
		return false;
	}

}